package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"time"
)

func init() {
	os.MkdirAll("data", os.ModePerm)
}
func main() {
	context.Background()
	stopChan := make(chan os.Signal)
	signal.Notify(stopChan, os.Interrupt)
	mux := http.NewServeMux()
	mux.Handle("/static/", http.FileServer(http.Dir("")))
	mux.Handle("/data/", http.FileServer(http.Dir("")))
	mux.Handle("/clean", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		form := r.Form
		fmt.Printf("%v\n%v\n", form, r.PostForm)
		os.RemoveAll("data")
		os.MkdirAll("data", os.ModePerm)
	}))
	mux.Handle("/write", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		_bytes, err := ioutil.ReadAll(r.Body)
		if err != nil {
			fmt.Println("err:%s", err.Error())
			return
		}
		strs := string(_bytes)
		fmt.Printf("xml:\n%s", strs)
		if _, err = os.Stat("data"); !os.IsExist(err) {
			if os.MkdirAll("data", 777) != nil {
				fmt.Printf("创建文件data失败:%s", err.Error())
			}
		}
		file, err := os.OpenFile(filepath.Join("data", time.Now().Format("2006-01-02(03-04-05.999999999).xml")),
			os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.ModePerm)
		if err != nil {
			fmt.Printf("err:%s", err.Error())
			return
		}
		defer file.Close()
		file.Write(_bytes)
	}))
	svr := &http.Server{Addr: ":8989", Handler: mux}
	if err := svr.ListenAndServe(); err != nil {
		log.Printf("listen:%s\n", err)
	}
	<-stopChan
	log.Println("shutting down server ...")

}
